# _*_ coding:utf-8 _*_
# @File  : application.py
# @Time  : 2021-10-25  13:56
# @Author: zizle
import re

from fastapi import APIRouter, Body, Query
from pydantic import BaseModel

from db import FAConnection
from status import r_status
from configs import WEB_HOST

application_api = APIRouter()


class ApplicationItem(BaseModel):
    company: str
    username: str
    phone: str
    client_code: str
    state: int = 0  # 状态 0-审核中 1-通过未发放账号 2-通过已发放账号 3-拒绝
    introducer: str = ''  # 推荐人为空且client_code=pcweb-yyb是营业部的人申请使用, pcweb则是通过网页申请使用的用户


@application_api.post('/', summary='申请用户的api')
async def application_users(apply_item: ApplicationItem = Body(...)):
    db = FAConnection(conn_name='添加申请')
    # 查询手机号是否已经存在了
    ret = db.query('SELECT id,phone,state FROM user_application WHERE phone=%s;', param=[apply_item.phone], fetchone=True, keep_conn=True)
    ret_obj = ret[0] if ret else {}
    if ret_obj:
        # 如果是被拒绝的用户，修改申请信息，再次发起的申请
        if ret_obj['state'] == 3:
            update_sql = 'UPDATE user_application SET company=%s,username=%s,phone=%s,client_code=%s,introducer=%s,' \
                         'state=0 WHERE id=%s LIMIT 1;'
            db.execute(update_sql, param=[apply_item.company, apply_item.username, apply_item.phone,
                                          apply_item.client_code, apply_item.introducer, ret_obj['id']])
            return {'code': r_status.VALIDATE_ERROR, 'message': '已成功再次提交申请，请等待管理员审核!'}
        db.close()
        return {'code': r_status.VALIDATE_ERROR, 'message': '该手机号已经提交过申请了，无需重复申请!'}
    # 查询手机号是否已经是用户了
    exists = db.query('SELECT id,phone FROM user_user WHERE phone=%s;', param=[apply_item.phone], fetchone=True, keep_conn=True)
    exists_obj = exists[0] if exists else {}
    if exists_obj:
        db.close()
        return {'code': r_status.CONTENT_EXISTS, 'message': '该手机号已经是我们用户了，无需再进行申请!'}

    # 添加申请记录
    # 通过client_code判断是用户还是营业部添加的请求，web-yyb是营业部，web-customer是客户，此时introducer推荐人是有数据的
    sql = 'INSERT INTO user_application (company,username,phone,client_code,state,introducer) ' \
          'VALUES (%s,%s,%s,%s,%s,%s);'
    _, s = db.insert(sql, param=[apply_item.company, apply_item.username, apply_item.phone,
                                 apply_item.client_code, apply_item.state, apply_item.introducer])

    if s:
        return {'code': r_status.CREATED_SUCCESS, 'message': '申请成功,等待管理人员审核.'}
    return {'code': r_status.VALIDATE_ERROR, 'message': '申请失败，服务器错误!'}


@application_api.get('/', summary='查询申请状态')
async def query_application_state(phone: str = Query(...)):
    # 验证手机号
    if not re.match(r'^1[13456789]\d{9}', phone):
        return {'code': r_status.VALIDATE_ERROR, 'message': '手机号格式有误,查无结果。', 'data': {}}
    sql = 'SELECT id,create_time,company,username,phone,state,introducer,description ' \
          'FROM user_application WHERE phone=%s;'
    db = FAConnection(conn_name='查询申请状态')
    ret_list = db.query(sql, param=[phone], fetchone=True)
    ret_obj = ret_list[0] if ret_list else {}
    if ret_obj:
        # 处理返回结果
        ret_obj['create_time'] = ret_obj['create_time'].strftime('%Y-%m-%d %H:%M:%S')
        ret_obj['state_msg'] = ''
        if ret_obj['state'] == 0:
            ret_obj['state_msg'] = '申请已提交,正等待处理···'
        elif ret_obj['state'] == 1:
            ret_obj['state_msg'] = '已通过，正在发放账号···'
        elif ret_obj['state'] == 2:
            ret_obj['state_msg'] = '恭喜申请通过，账号已生成!'
            # 账号已生成则添加信息
            ret_obj['download_url'] = WEB_HOST + 'installer/otdownload.html'
        elif ret_obj['state'] == 3:
            ret_obj['state_msg'] = '很遗憾,申请不通过：【' + ret_obj['description'] + '】\n您可以填写完整信息再次发起申请!'
        else:
            pass
        return {'code': r_status.SUCCESS, 'message': '查询成功!', 'data': ret_obj}
    else:
        return {'code': r_status.NOT_CONTENT, 'message': '没有您的申请记录!', 'data': {}}